package com.innovation.chengzhangriji.ui.agent;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Discover;
import com.innovation.chengzhangriji.DiscoverPhoto;
import com.innovation.chengzhangriji.DiscoverSaveComment;
import com.innovation.chengzhangriji.TimelineLastServerTime;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.DiscoverTimelineActivity;
import com.innovation.chengzhangriji.ui.model.DTModel;
import com.innovation.chengzhangriji.util.BabyUtil;
import com.innovation.chengzhangriji.util.FileUtils;

import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class DiscoverTimelineAgent {

    /**
     * 宝宝信息
     */
    private Baby baby;
    public Baby getBaby() {
        return baby;
    }

    /**
     * 当前宝宝的称谓
     */
    private String role;

    private SoftReference<DiscoverTimelineActivity> context;

    public ArrayList<DTModel> getDiscoverList() {
        return discoverList;
    }

    // 日记列表
    private ArrayList<DTModel> discoverList = new ArrayList<>();

    public DiscoverTimelineAgent(DiscoverTimelineActivity activity, int babyId) {
        context = new SoftReference<>(activity);
        baby = DatabaseManager.getInstance(activity).queryBaby(babyId);
        role = baby.getParentName();
    }

    /**
     * 下拉刷新->获取宝宝信息
     */
    public void requestBabyInfo() {
        Config.startGetAllBabyInfoService(context.get());
    }

    /**
     * 下拉刷新->获取关注人信息
     */
    public void requestBabyParentInfo() {
        Config.startGetAllParentInfoService(context.get());
    }

    /**
     * 开启数据刷新服务
     */
    public void startSync() {
        if(context.get() != null) {
            Config.startSyncTimelineService(context.get());
            // 检查新评论
            Bundle bundle = new Bundle();
            bundle.putBoolean("autoCheck", true);
            Config.startLocalCommentService(context.get(), bundle);
        }
    }

    /**
     * 刷新宝宝信息
     */
    public void refreshBaby() {
        if(context.get() != null && baby != null) {
            baby = DatabaseManager.getInstance(context.get()).queryBaby(baby.getBabyID());
            role = baby.getParentName();
        }
    }

    /**
     * 同步完成
     */
    public void syncComplete() {
        if (context.get() == null) {
            return;
        }
        loadLocalTopNewDiary();
        // Config.startDownloadTimelineService(context.get());
    }

    /**
     * 加载更多
     */
    public void loadMore() {

        // 先获取本地的数据
        long lastCreateTs = discoverList.get(discoverList.size() - 1).getDiscover().getCreateTS();
        List<DTModel> models = DatabaseManager.getInstance(context.get()).queryOldDiscoverTimeline(baby.getBabyID(), Config.QUERY_LENGTH, lastCreateTs);
        if (models.size() > 0) {
            discoverList.addAll(models);
            // 检查新评论
            Bundle bundle = new Bundle();
            bundle.putBoolean("autoCheck", true);
            Config.startLocalCommentService(context.get(), bundle);
        } else {
            // 加载网络
            Config.startLoadTimelineService(context.get());
        }
    }

    /**
     * 加载更多完成
     */
    public void loadComplete(long createTS) {
        List<DTModel> models = DatabaseManager.getInstance(context.get()).queryOldDiscoverTimeline(baby.getBabyID(), Config.QUERY_LENGTH, createTS);
        discoverList.addAll(models);
    }

    /**
     * 查询剩余时间戳
     */
    private TimelineLastServerTime queryLastServerTime(String uuid) {
        LoginInfo loginInfo = Config.getLoginInfo(context.get());
        if (loginInfo == null) {
            return null;
        }
        int babyID = loginInfo.getBabyID();
        return DatabaseManager.getInstance(context.get()).queryLastServerTime(babyID, uuid);
    }

    /**
     * 加载本地最新的 n 条日记
     */
    public void loadLocalTopNewDiary() {
        discoverList.clear();
        discoverList.addAll(DatabaseManager.getInstance(context.get()).queryDiscoverTimeline(baby.getBabyID(), Config.QUERY_LENGTH));
    }

    // -- 发表日记模块开始 --

    // 发表文字日记
    public void sendMessage(String text) {

        DTModel model = new DTModel();
        // 日记信息
        Discover discover = new Discover();
        setBasedDiscoverData(discover);
        discover.setText(text);
        discover.setType(1);
        model.setDiscover(discover);
        // 设置评论和赞
        model.setCommentList(new ArrayList<DiscoverSaveComment>());
        model.setLikeList(new ArrayList<DiscoverSaveComment>());
        discoverList.add(0, model);

        // 把日记保存到本地
        DatabaseManager.getInstance(context.get()).insertOrReplaceDiscover(discover, null);

        // 插入上传的信息，启动上传
        insertText(Config.getLoginInfo(context.get()), discover.getCreateTS(), discover.getDiaryID(), text, baby.getState());
        Config.startUploadTimelineService(context.get());
    }


    // 发送照片日记
    public void sendPhoto(String theme, String text, String[] urls) {
        DTModel model = new DTModel();

        // 日记信息
        Discover discover = new Discover();
        setBasedDiscoverData(discover);
        discover.setText(text);
        discover.setTheme(theme);
        discover.setType(2);
        model.setDiscover(discover);

        // 日记照片
        ArrayList<DiscoverPhoto> photos = new ArrayList<>();
        String[] newUrls = new String[urls.length];
        for (int i = 0; i < urls.length; i++) {
            File file = Config.createFile(context.get(), Config.PHOTO_DIR);
            File source = new File(urls[i]);
            try {
                FileUtils.copyFileUsingFileChannels(source, file);
                DiscoverPhoto photo = new DiscoverPhoto();
                photo.setDiscoverID(discover.getDiaryID());
                photo.setUrl(file.getPath());
                newUrls[i] = file.getPath();
                photos.add(photo);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        model.setPhotoList(photos);
        // 设置评论和赞
        model.setCommentList(new ArrayList<DiscoverSaveComment>());
        model.setLikeList(new ArrayList<DiscoverSaveComment>());
        discoverList.add(0, model);

        // 把日记保存到本地
        DatabaseManager.getInstance(context.get()).insertOrReplaceDiscover(discover, newUrls);

        // 插入上传的信息，启动上传
        insertPhoto(Config.getLoginInfo(context.get()), discover.getCreateTS(), discover.getDiaryID(), text, theme, newUrls, baby.getState());
        Config.startUploadTimelineService(context.get());
    }

    // 发送音频日记
    public void sendAudio(int length, String path) {
        DTModel model = new DTModel();

        // 日记信息
        Discover discover = new Discover();
        setBasedDiscoverData(discover);
        discover.setAudioLocalUrl(path);
        discover.setDuration(length);
        discover.setType(3);
        model.setDiscover(discover);
        // 设置评论和赞
        model.setCommentList(new ArrayList<DiscoverSaveComment>());
        model.setLikeList(new ArrayList<DiscoverSaveComment>());
        discoverList.add(0, model);

        // 把日记保存到本地
        DatabaseManager.getInstance(context.get()).insertOrReplaceDiscover(discover, null);

        // 插入上传的信息，启动上传
        insertAudio(Config.getLoginInfo(context.get()), discover.getCreateTS(), discover.getDiaryID(), length, path, baby.getState());
        Config.startUploadTimelineService(context.get());
    }

    // 发送视频日记
    public void sendVideo(String screenshotUrl, int length, String path) {
        DTModel model = new DTModel();

        // 日记信息
        Discover discover = new Discover();
        setBasedDiscoverData(discover);
        discover.setVideoLocalUrl(path);
        discover.setScreenshot(screenshotUrl);
        discover.setDuration(length);
        discover.setType(4);
        model.setDiscover(discover);
        // 设置评论和赞
        model.setCommentList(new ArrayList<DiscoverSaveComment>());
        model.setLikeList(new ArrayList<DiscoverSaveComment>());
        discoverList.add(0, model);

        // 把日记保存到本地
        DatabaseManager.getInstance(context.get()).insertOrReplaceDiscover(discover, null);

        // 插入上传的信息，启动上传
        insertVideo(Config.getLoginInfo(context.get()), discover.getCreateTS(), discover.getDiaryID(), screenshotUrl, length, path, baby.getState());
        Config.startUploadTimelineService(context.get());
    }

    // 发表第一次日记
    public void sendMilestone(String milestone, int milestoneId) {
        DTModel model = new DTModel();

        // 日记信息
        Discover discover = new Discover();
        setBasedDiscoverData(discover);
        discover.setMilestone(milestone);
        discover.setType(1);
        model.setDiscover(discover);
        // 设置评论和赞
        model.setCommentList(new ArrayList<DiscoverSaveComment>());
        model.setLikeList(new ArrayList<DiscoverSaveComment>());
        discoverList.add(0, model);

        // 把日记保存到本地
        DatabaseManager.getInstance(context.get()).insertOrReplaceDiscover(discover, null);

        // 插入上传的信息，启动上传
        insertMilestone(Config.getLoginInfo(context.get()), discover.getCreateTS(), discover.getDiaryID(), milestoneId, milestone, baby.getState());
        Config.startUploadTimelineService(context.get());
    }

    // 初始化共同的日记信息
    private void setBasedDiscoverData(Discover discover) {

        LoginInfo loginInfo = Config.getLoginInfo(context.get());
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        discover.setDiaryID(uuid);
        discover.setIsDelete(false);
        discover.setIsLocal(true);
        discover.setCreateTS(System.currentTimeMillis());
        discover.setBabyID(baby.getBabyID());
        discover.setBabyHeadUrl(baby.getImageUrl());
        discover.setBabyName(baby.getName());
        discover.setDiaryName(BabyUtil.getBabyNoteName(baby));
        discover.setGrowthStageID(baby.getState());
        discover.setMemberName(role);
        discover.setUserHeadUrl(loginInfo.getUrl());
        discover.setDiaryFrom(1); // 来自日记本
        discover.setNickName(loginInfo.getName());
        discover.setUserID(loginInfo.getUserID());
    }

    private void insertText(LoginInfo login, long localTime, String uuid, String text, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(context.get()).insertTimelineText(uuid, babyID, userID, role, state, localTime, text);
    }

    private void insertPhoto(LoginInfo login, long localTime, String uuid, String text, String theme, String[] localUrls, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(context.get()).insertTimelinePhoto(uuid, babyID, userID, role, state, localTime, text, theme, localUrls);
    }

    private void insertAudio(LoginInfo login, long createTS, String uuid, int length, String localUrl, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(context.get()).insertTimelineAudio(uuid, babyID, userID, role, state, createTS, length, localUrl);
    }

    private void insertVideo(LoginInfo login, long createTS, String uuid, String screenshotUrl, int length, String localUrl, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(context.get()).insertTimelineVideo(uuid, babyID, userID, role, state, createTS, screenshotUrl, length, localUrl);
    }

    private void insertMilestone(LoginInfo login, long localTime, String uuid, int milestoneID, String milestone, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(context.get()).insertTimelineMilestone(uuid, babyID, userID, role, state, localTime, milestoneID, milestone);
    }

    // -- 发表日记模块结束 --

}
